<template>
  <el-popover placement="bottom" :width="len" trigger="click" :visible="visible">
    <template #reference>
      <el-button class="btnview" v-if="conditionItem" @click="buttonVisible()">
        <span class="f13">{{ titleName }}</span>
        <el-icon class="el-icon-circle-close el-icon--right" @click="deleteAction"><CircleClose /></el-icon>
      </el-button>
      <el-button class="btnview" @click="addnew" v-else>
        <el-icon><Plus /></el-icon>
        <span class="f13">新增</span>
      </el-button>
    </template>
    <el-row>
      <el-col :span="8">
        <el-select
          v-model="nameStr"
          placeholder="请选择"
          @change="getOpValue"
          filterable
          :allow-create="false"
        >
          <el-option
            v-for="(item, index) in firstOptionsBak"
            :key="index"
            :label="item.fieldName"
            :value="item.fieldName"
            :disabled="item.disabled"
          >
            <i :class="item.fieldClass==2?'iconfont icon-dimensions':'iconfont icon-zhibiao'" style="font-size: 14px">
              <span style="margin-left: 5px">{{item.fieldName}}</span>
            </i>
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-select v-model="value2" placeholder="请选择" @change="selectwhereTp">
          <el-option
            v-for="(item, index) in options2"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="8">
        <!-- 单选 -->
        <el-select
          filterable
          v-model="whereValue"
          remote
          reserve-keyword
          remote-show-suffix
          placeholder="请选择"
          v-if="valueType == 'normal'"
          @change="emitData"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="(item, index) in options3"
            :key="index"
            :label="item.itemName"
            :value="item.itemName"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="whereValue"
          format="YYYYMM"
          value-format="YYYYMM"
          type="month"
          @change="emitData"
          v-if="valueType == 'month'"
          placeholder="选择日期"
          style="width: fit-content"
        />
        <el-date-picker
          v-model="whereValue"
          type="date"
          placeholder="选择日期"
          v-if="valueType == 'day'"
          format="YYYYMMDD"
          value-format="YYYYMMDD"
          @change="emitData"
          style="width: fit-content"
        >
        </el-date-picker>

        <!-- 多选 -->
        <el-select
          v-model="whereVarr"
          multiple
          placeholder="请选择"
          v-if="valueType == 'mutle'"
          @change="emitData"
          @blur="removeAc"
          :remote-method="remoteMethod"
          :loading="loading"
        >
          <el-option
            v-for="(item, index) in options3"
            :key="index"
            :label="item.itemName"
            :value="item.itemVal"
          >
          </el-option>
        </el-select>

        <el-date-picker
                popper-class="qujian"
                v-model="whereVarr"
                type="monthrange"
                @change="mutblMDate"
                v-if="valueType == 'beM'"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份">
        </el-date-picker>
        <el-date-picker
                v-model="whereVarr"
                type="daterange"
                @change="mutblDDate"
                v-if="valueType == 'beD'"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
        </el-date-picker>

        <!-- 输入框 -->
        <el-input
          v-model="whereValue"
          placeholder="请输入内容"
          v-if="valueType == 'ipt'"
          @change="emitData"
        ></el-input>
      </el-col>
    </el-row>
  </el-popover>
</template>
<script>
import { getValFromCd } from '@/api/chartdb'
import { transCodeToStr } from './util.js'
import consts from '../../common/consts'
import mom from 'moment'
export default {
  setup() {
    //动态加载css
    let cssPath="";
    let mode=localStorage.getItem("mode")
    if(mode=="dark"){
      cssPath = import("/src/assets/css/dark/index.scss");
    }else if(mode=="light"){
      cssPath = import("/src/assets/css/light/index.scss");
    }
    return {
      cssPath
    };
  },
  props: {
    tname: {},
    firstOptions: {type:Array},
    tableId: {},
    conditionItem: {},
    condition:{type:Array},
    sIndex: {},
  },
  data() {
    return {
      nameStr: '',
      nameObj: {},
      options: '',
      options2: [
        { label: '等于', value: '=' },
        { label: '大于', value: '>' },
        { label: '小于', value: '<' },
        { label: '小于等于', value: '<=' },
        { label: '大于等于', value: '>=' },
        { label: '类似', value: 'LIKE' },
        { label: '包含', value: 'IN' },
        { label: '区间', value: 'BETWEEN' },
        { label: '是', value: 'IS NULL' },
        { label: '不是', value: 'IS NOT NULL' }
      ],
      options3: [],
      value2: '=',
      whereValue: '',
      len:400,
      whereVarr: [],
      valueType: 'normal', //month月选择  day日选择  normal单选择器  doubleSelectDate 开始结束时间选择  ipt 输入框
      titleName: '',
      visible: false,
      loading:false,
      level_list_option:consts.level_list_option,
      level_list_option_1:consts.level_list_option_1,
      level:0,
      parentId:'',
      parentDictList:[],
      firstOptionsBak:[],
    }
  },
  watch:{
    firstOptions:{
      handler(newVal) {
        this.firstOptionsBak=[]
        this.firstOptions.forEach(item=>{
          var bak=JSON.parse(JSON.stringify(item))
          if(this.conditionItem
            &&item.fieldCode==this.conditionItem.fieldCode){
            // item.disabled=true
            bak.disabled=false
          }else {
            // item.disabled=false
            // bak.disabled=false
          }
          this.firstOptionsBak.push(bak)
        })
      }
    },
    condition:{
      handler(newVal) {
        this.parentDictList=[]
        newVal.forEach(item=>{
          if(this.level_list_option[item.fieldCode]){
            var parentDict={
              level:this.level_list_option[item.fieldCode],
              parentId:item.fieldCode
            }
            this.parentDictList.push(parentDict)
          }
        })
      },
      deep: true // 开启深度观测
    },
    // conditionItem:{
    //   handler(newVal) {
    //     console.log("conditionItem===========>>>>>",newVal)
    //     let whname = this.conditionItem.whereValueName
    //         ? this.conditionItem.whereValueName
    //         : this.conditionItem.whereValue
    //     this.titleName = this.conditionItem.fieldName + transCodeToStr(this.conditionItem.whereType) + whname
    //   },
    //   deep: true // 开启深度观测
    // }
  },
  mounted() {
    // console.log("firstOptions======>",this.firstOptions)
  },
  created() {
    this.init()
  },

  methods: {
    init(){
      this.condition.forEach(item=>{
        if(this.level_list_option[item.fieldCode]){
          var parentDict= {
            level: this.level_list_option[item.fieldCode],
            parentId: item.fieldCode
          }
          this.parentDictList.push(parentDict)
        }
        this.parentDictList=Array.from(new Set(this.parentDictList.map((obj) => JSON.stringify(obj)))).map((strObj) => JSON.parse(strObj));

      })
      if (this.conditionItem) {
        this.nameObj = this.conditionItem
        this.nameStr = this.conditionItem.fieldName
        this.value2 = this.conditionItem.whereType
        this.judgeValueType(this.conditionItem)
        let whname = this.conditionItem.whereValueName
            ? this.conditionItem.whereValueName
            : this.conditionItem.whereValue
        whname=whname.replace(/\'/g,"")
        if(this.nameObj.fieldType==1&&this.nameObj.whereType=='='){
          // this.nameObj.whereValue="'"+this.nameObj.whereValue+"'"
          this.nameObj.whereValue=this.nameObj.whereValue
        }
        if(this.value2=='BETWEEN'){
          let arrList=whname.split(",")
          // arrList.forEach(item=>{
          //   this.whereValue.
          // })
          this.len=590
          this.whereVarr=arrList
        }else {
          this.whereValue=whname
        }
        this.whereValue=this.whereValue.replace(/\'/g,"")
        this.titleName = this.conditionItem.fieldName + transCodeToStr(this.conditionItem.whereType) + whname
        this.value3 = this.conditionItem.whereValue
      } else {
      }
    },
    buttonVisible() {
      if(this.firstOptionsBak.length==0){
        this.firstOptions.forEach(item=>{
          var bak=JSON.parse(JSON.stringify(item))
          if(this.conditionItem
            &&item.fieldCode==this.conditionItem.fieldCode){
            // item.disabled=true
            bak.disabled=false
          }else {
            // item.disabled=false
            // bak.disabled=false
          }
          this.firstOptionsBak.push(bak)
        })
      }
      // if (this.value2 == 'BETWEEN') {
      //   this.visible = false
      // } else {
      //   this.visible = !this.visible
      // }
      this.judgeValueType(this.conditionItem);
      this.visible = !this.visible
      this.$emit('closeOtherPo', this.sIndex)
    },
    addnew() {
      this.visible = !this.visible
      this.nameStr = null
      this.whereValue = ''
      this.$emit('closeOtherPo', this.sIndex)
    },
    closePopover(){
      this.visible = false
    },
    clearRestData() {
      this.nameObj = {}
      this.value2 = '='
      this.titleName = ''

      this.newwhereValue = {}
    },
    selectwhereTp(wv) {
      if (wv == 'IN' || wv == 'NOT IN') {
        this.valueType = 'ipt'
        this.len=400
      }else if(wv == 'BETWEEN'&&this.nameObj.fieldCode.startsWith('MONTH_ID')){
        this.len=590
        this.valueType = 'beM'
      }else if(wv == 'BETWEEN'&&this.nameObj.fieldCode.startsWith('DAY_ID')){
        this.len=590
        this.valueType = 'beD'
      }
    },
    remoteMethod(query){
      if(query){
        this.loading=true
        let parentFieldCode=this.getParentCode(this.nameObj.fieldCode)
        const param = { modelId: this.tableId,
          fieldCode: this.nameObj.fieldCode,
          keyword: query,
          limit: 20,
          parentFieldCode:parentFieldCode,
          tableCode:''
        }
        getValFromCd(param).then((respo) => {
          this.loading=false
          const res = respo.data.data
          if(res&&res.length>0){
            this.options3 = res
          }
          this.valueType = 'normal'
        })
      }else {
        this.options3 = []
      }

    },
    //判断数据类型
    judgeValueType(mObj) {
      //in  not in
      // if (mObj.whereType == 'IN' || mObj.whereType == 'NOT IN') {
      //   this.valueType = 'mutle'
      // } else if(mObj.fieldCode == 'MONTH_ID'){
      //   this.valueType = 'month'
      // } else if (mObj.fieldCode == 'DAY_ID') {
      //   this.valueType = 'day'
      // } else if (mObj.isItem == 1) {
      //   this.valueType = 'normal'
      // } else {
      //   this.valueType = 'ipt'
      // }

      if(mObj.fieldCode.startsWith('MONTH_ID')){
        if(mObj.whereType == 'BETWEEN'){
          this.valueType = 'beM'
        }else if(mObj.whereType == 'IN' || mObj.whereType == 'NOT IN'){
          this.valueType = 'ipt'
        }else {
          this.valueType = 'month'
        }
      }else if(mObj.fieldCode.startsWith('DAY_ID')){
        if(mObj.whereType == 'BETWEEN'){
          this.valueType = 'beD'
        }else if(mObj.whereType == 'IN' || mObj.whereType == 'NOT IN'){
          this.valueType = 'ipt'
        }else {
          this.valueType = 'day'
        }
      } else if (mObj.isItem == 1){
        let parentFieldCode=this.getParentCode(mObj.fieldCode)
        const param = { modelId: this.tableId, fieldCode: mObj.fieldCode, keyword: "", limit: 20, parentFieldCode:parentFieldCode,tableCode:'' }
        getValFromCd(param).then((respo) => {
          const res = respo.data.data
          if(res&&res.length>0){
            this.options3 = res
          }
          this.valueType = 'normal'
        })
        if (mObj.whereType == 'IN' || mObj.whereType == 'NOT IN') {
          this.valueType = 'mutle'
        }else if (mObj.whereType == 'IS NULL' || mObj.whereType == 'IS NOT NULL') {
          this.valueType = 'ipt'
        }else {
          this.valueType = 'normal'
        }
      }else {
        this.valueType = 'ipt'
      }

      // if (mObj.fieldCode == 'MONTH_ID') {
      //   this.valueType = 'month'
      // } else if (mObj.fieldCode == 'DAY_ID') {
      //   this.valueType = 'day'
      // } else if (mObj.isItem == 1) {
      //   const param = { modelId: this.tableId, fieldCode: mObj.fieldCode }
      //   getValFromCd(param).then((respo) => {
      //     const res = respo.data.data
      //     if(res&&res.length>0){
      //       this.options3 = res
      //     }
      //     this.valueType = 'normal'
      //   })
      //   if (mObj.whereType == 'IN' || mObj.whereType == 'NOT IN') {
      //     this.valueType = 'mutle'
      //   } else {
      //     this.valueType = 'normal'
      //   }
      // } else {
      //   this.valueType = 'ipt'
      // }
    },
    getParentCode(fieldCode){
      let curLevel=this.level_list_option[fieldCode];
      let level=0
      let parentFieldCode=""
      this.parentDictList.forEach(item=>{
        if(curLevel&&curLevel>item.level){
          if(level<item.level){
            level=item.level
            parentFieldCode=item.parentId
          }
        }
      })
      return parentFieldCode
    },
    deleteAction(val) {
      this.$emit('changeConditionItem', this.sIndex)
    },
    getOpValue(value) {
      // debugger
      this.nameStr = value
      this.nameObj = this.firstOptions.find((item) => item.fieldName === value)
      this.judgeValueType(this.nameObj)
      this.visible=true
    },
    //多选
    mutblEmitData(mutbleStr) {
      const mt = mutbleStr
      // debugger
    },
    mutblMDate(mutbleStr) {
      // const mt = mutbleStr
      this.whereVarr=[]
      mutbleStr.forEach(item=>{
        this.whereVarr.push(mom(item).format("YYYYMM"))
      })
      var newCo=this.whereVarr[0]+' AND '+this.whereVarr[1]
      this.emitData(newCo)
      // debugger
    },
    mutblDDate(mutbleStr) {
      // const mt = mutbleStr
      this.whereVarr=[]
      mutbleStr.forEach(item=>{
        this.whereVarr.push(mom(item).format("YYYYMMDD"))
      })
      var newCo=this.whereVarr[0]+' AND '+this.whereVarr[1]
      this.emitData(newCo)
      // debugger
    },
    removeAc(val) {
      // debugger
    },
    //组装数据上传
    emitData(currenStr) {
      // debugger
      var whValue = currenStr
      if(this.valueType=='beM'){
        // whValue=currenStr
        currenStr=currenStr.split(" AND ")[0]+","+currenStr.split(" AND ")[1]
      }else if(this.valueType=='beD'){
        // whValue=currenStr
        currenStr=currenStr.split(" AND ")[0]+","+currenStr.split(" AND ")[1]
      }else if (this.valueType == 'day' || this.valueType == 'month') {
        // whValue = currenStr
      }else if (this.value2 == 'IN' || this.valueType == 'NOT IN') {
        // whValue = currenStr
      } else {
      }
      whValue=currenStr
      var whValueName = currenStr
      // var whValue = currenStr
      if (this.valueType == 'normal') {
        const currentV = this.options3.find((item) => item.itemName === currenStr)
        if(currentV.itemVal){
          whValue =  currentV.itemVal
        }
        whValueName = currentV.itemName
      }

      if (this.value2 == 'LIKE') {
        whValue = "'%" + currenStr + "%'"
      }
      const currentobj = this.firstOptions.find((item) => item.fieldCode === this.nameObj.fieldCode)
      var pardata = {
        fieldCode: currentobj.fieldCode,
        fieldName: currentobj.fieldName,
        fieldType: currentobj.fieldType,
        isItem: currentobj.isItem,

        whereType: this.value2,
        whereValue: whValue,
        whereValueName: whValueName
      }

      const whname = pardata.whereValueName ? pardata.whereValueName : pardata.whereValue
      this.titleName = pardata.fieldName + transCodeToStr(pardata.whereType) + whname
      //变更
      if (this.conditionItem) {
        this.$emit('changeConditionItem', this.sIndex, pardata)
      } else {
        //新增
        this.$emit('addConditionData', pardata)
      }
      this.visible = false
    }
  }
}
</script>
<style scoped>
/*@import './index.css';*/
.btnview {
  padding: 5px 10px;
}
.f13 {
  font-size: 13px;
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: auto;
}
.dpview {
  width: fit-content;
}
.el-button{
    margin-left: 0px !important;
    margin-right: 12px !important;
    margin-bottom: 5px !important;
}
  .sure-button{
    text-align: right;
    margin: 5px 0px 0px 0;
  }
.sure-button button{
  margin: 0px !important;
}
:deep(.el-range-editor.el-input__wrapper) {
  display: inline-flex;
  align-items: center;
  padding: 0 10px;
  width: 190px !important;
}
</style>